package com.paas.demo.shiro;

import com.paas.demo.shiro.entity.User;
import com.paas.demo.shiro.service.PermService;
import com.paas.demo.shiro.service.RoleService;
import com.paas.demo.shiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @ClassName : ShiroCustomRealm
 * @Description : Shiro 鉴权类
 * @author : pengjie
 * @email  : 627799251@qq.com
 * @version
 * @Date : 2019/1/21 13:07
*/
public class ShiroCustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermService permService;


    //定义如何获取用户的角色和权限的逻辑，给shiro做权限判断
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //null usernames are invalid
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }

        ShiroUser user = (ShiroUser) getAvailablePrincipal(principals);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        System.out.println("获取角色信息："+user.getRoles());
        System.out.println("获取权限信息："+user.getPerms());
        info.setRoles(user.getRoles());
        info.setStringPermissions(user.getPerms());
        return info;
    }

    //定义如何获取用户信息的业务逻辑，给shiro做登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        ShiroUserToken upToken = (ShiroUserToken) token;
        String username = upToken.getUsername();

        // Null username is invalid
        if (username == null) {
            throw new AccountException("Null usernames are not allowed by this realm.");
        }

        ShiroUser shiroUser = getShiroUser(upToken);

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(shiroUser, shiroUser.getPwd(), getName());
        if (shiroUser.getSalt() != null) {
            info.setCredentialsSalt(ByteSource.Util.bytes(shiroUser.getSalt()));
        }

        return info;

    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof ShiroUserToken;
    }

    private ShiroUser getShiroUser(ShiroUserToken userToken){

        ShiroUser shiroUser = null;

        String username = userToken.getUsername();

        switch (userToken.getTokentype()){
            case sys:
                User userDB = userService.findUserByName(username);
                if (userDB == null) {
                    throw new UnknownAccountException("No account found for sys [" + username + "]");
                }
                shiroUser = new ShiroUser(userDB);
                //查询用户的角色和权限存到SimpleAuthenticationInfo中，这样在其它地方
                //SecurityUtils.getSubject().getPrincipal()就能拿出用户的所有信息，包括角色和权限
                Set<String> roles = roleService.getRolesByUserId(userDB.getUid());
                Set<String> perms = permService.getPermsByUserId(userDB.getUid());
                shiroUser.getRoles().addAll(roles);
                shiroUser.getPerms().addAll(perms);
                break;
            case app:
                break;
            case tv:
                break;
        }
        return shiroUser;
    }
}
